package com.myphoto.base.util;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;

public class SsoSecret {

	/**
	 * 执行AES方式加密
	 * @最后修改人	方安伦
	 * @修改时间	2014-12-24 上午9:56:58
	 * @param value
	 * @return
	 */
	public static String encryptAES(String value){
		String strRet = null;
		try{
			//实例化密钥对象
			SecretKey secretKey = new SecretKeySpec(Base64.decodeBase64(ConstantsCookie.DEFAULT_SECRET_KEY),"AES");
			//获取密码加解密对象
			Cipher cipher = Cipher.getInstance("AES");
			//加密模式
			cipher.init(Cipher.ENCRYPT_MODE, secretKey);
			//加密，得到加密后的byte数组
			byte[] encryptedBytes = cipher.doFinal(value.getBytes("UTF-8"));
			//转为base64编码
			strRet = Base64.encodeBase64String(encryptedBytes);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return strRet;
	}

	/**
	 * 执行AES方式解密
	 * @最后修改人	方安伦
	 * @修改时间	2014-12-24 上午10:01:18
	 * @param value
	 * @return
	 */
	public static String decryptAES(String value){
		String strRet = null;
		try {
			byte[] valueBytes = Base64.decodeBase64(value);
			//同样构造密钥对象
			SecretKey secretKeySpec = new SecretKeySpec(Base64.decodeBase64(ConstantsCookie.DEFAULT_SECRET_KEY),"AES");
			//加解密对象
			Cipher cipher = Cipher.getInstance("AES");
			//解密模式
			cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
			//解密，并得到明文的字符串
			strRet = new String(cipher.doFinal(valueBytes),"UTF-8");
		} catch (Exception e) {
		}
		return strRet;
	}

	/**
	 * 执行MD5加密
	 * @最后修改人	方安伦
	 * @修改时间	2014-12-24 上午10:04:07
	 * @param value
	 * @return
	 */
	public static String MD5(String value){
		String strRet = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(value.getBytes("UTF-8"));
			byte[] out = md.digest();
			StringBuffer sb = new StringBuffer();
			for(int i=0;i<out.length;i++){
				String hex = Integer.toHexString(out[i]&0xFF);
				if(hex.length()<2){
					sb.append(0);
				}
				sb.append(hex);
			}
			strRet = sb.toString();
		} catch (Exception e) {
		}
		return strRet;
	}

}
